//
//  MessageManager.m
//  gdemm
//
//  Created by 乔明超 on 16/5/10.
//  Copyright © 2016年 Goldencis. All rights reserved.
//

#import "MessageManager.h"
#import "MessageInfo.h"
#import "UserDefaultsUtil.h"
#import "ApiSupport.h"
#import "HttpUtil.h"
#import "FMDB.h"
@interface MessageManager()
@property (nonatomic,assign) BOOL mFetched;
@property (nonatomic,strong) FMDatabaseQueue *queue;
@end
@implementation MessageManager
static MessageManager *mInstance;
- (FMDatabaseQueue *)queue{
    if (_queue == nil) {
        NSString *path = [NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"gdemm.db"];
        _queue = [FMDatabaseQueue databaseQueueWithPath:path];
        [_queue inDatabase:^(FMDatabase *db) {
            if ([db open]) {
                if ([db executeUpdate:@"create table if not exists t_gdemm (ID integer primary key autoincrement,accountName text not null,noticeTitle text not null,noticeTime text not null,noticeCon text not null,userGuid text not null,selected interger not null,isRead integer not null)"]) {
                    
                }
                
            }
            
        }];
        
    }
    return _queue;
}
+ (instancetype)getInstance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        mInstance = [[self alloc]init];
    });
    
    return mInstance;
}
- (NSMutableArray *)getAllMessages:(NSString *)userGuid{
    NSMutableArray *messagesArray = [NSMutableArray array];
    [self.queue inDatabase:^(FMDatabase *db) {
        FMResultSet *resultSet =[db executeQueryWithFormat:@"select * from t_gdemm where userGuid = %@ order by noticeTime desc",userGuid];
        while ([resultSet next]) {
            MessageInfo *messageInfo = [[MessageInfo alloc]init];
            messageInfo.ID = [resultSet intForColumn:@"ID"];
            messageInfo.accountName = [resultSet stringForColumn:@"accountName"];
            messageInfo.noticeTitle = [resultSet stringForColumn:@"noticeTitle"];
            messageInfo.noticeTime = [resultSet stringForColumn:@"noticeTime"];
            messageInfo.noticeCon = [resultSet stringForColumn:@"noticeCon"];
            messageInfo.userGuid = [resultSet stringForColumn:@"userGuid"];
            messageInfo.selected = [resultSet intForColumn:@"selected"];
            messageInfo.isRead = [resultSet intForColumn:@"isRead"];
            [messagesArray addObject:messageInfo];
        }
  
    }];
       return messagesArray;
}
- (void)loadThread{

    self.mFetched = YES;
    NSString *url = [ApiSupport getMessageSyncUrl];
    if (url == nil) {
        return;
    }
    NSDictionary *dict = [HttpUtil downloadToMemory:url];
    HRLog(@"url = %@ dict = %@",url,dict);
    if ([dict[@"result"] isEqualToString:@"success"]) {
        NSArray *messageList = dict[@"noticeList"];
        if (messageList.count != 0) {
            NSArray *messageInfoList = [MessageInfo messageWithArray:dict[@"noticeList"]];
            for (MessageInfo *messageInfo in messageInfoList) {
                messageInfo.userGuid = [[UserDefaultsUtil shareInstance]getString:LC_USERGUID];
                messageInfo.isRead = NO;
                messageInfo.selected = NO;
                [self addMessge:messageInfo];
            }
            
        }
    }
}

- (void)loadCloundFileInfo:(BOOL)backgroud{
    if (backgroud) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [self loadThread];
        });
    }else{
        [self loadThread];
    }
}


- (void)addMessge:(MessageInfo *)messgeInfo{
    [self.queue inDatabase:^(FMDatabase *db) {
        [db executeUpdateWithFormat:@"insert into t_gdemm(accountName,noticeTitle,noticeTime,noticeCon,userGuid,selected ,isRead) values (%@,%@,%@,%@,%@,%d,%d)",messgeInfo.accountName,messgeInfo.noticeTitle,messgeInfo.noticeTime,messgeInfo.noticeCon,messgeInfo.userGuid,messgeInfo.selected,messgeInfo.isRead];
    }];
    
}

- (void)deleteMessageById:(long)ID{
    NSString *sqlStr = [NSString stringWithFormat:@"DELETE FROM t_gdemm where id = %ld",ID];
    [self.queue inDatabase:^(FMDatabase *db) {
        [db executeUpdate:sqlStr];
    }];
}
- (void)setReadedById:(long)ID{
    NSString *sqlStr =[NSString stringWithFormat:@"update t_gdemm set isRead = 1 where ID = %ld",ID];
    [self.queue inDatabase:^(FMDatabase *db) {
        [db executeUpdate:sqlStr];
    }];
}

- (NSInteger)getUnreadCount{
    if (!self.mFetched) {
        [self loadCloundFileInfo:NO];
        
    }
    __block NSInteger count = 0;
    NSString *sqlStr = @"select * from t_gdemm where isRead = 0";
    [self.queue inDatabase:^(FMDatabase *db) {
        FMResultSet *rs = [db executeQuery:sqlStr];
        while ([rs next]) {
            count++;
        }

    }];
    
    return count;
}

- (void)clearMessage{
    NSString *sqlStr = [NSString stringWithFormat:@"DELETE FROM t_gdemm"];
    [self.queue inDatabase:^(FMDatabase *db) {
        [db executeUpdate:sqlStr];
    }];
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"AlertsReloadData" object:nil];
}
@end
